#include "testIntrinsicImage.h"
#include "cvxImage.h"
#include <iostream>
#include <time.h>
#include <vector>
#include <algorithm>
#include <list>
#include "nvmath.h"
#include "least_square.h"
#include "cvxQuadTree.h"
#include "cvxSf.h"
#include "cvxStroke.h"
#include "cvxIntrinsicSolver.h"
#include "cvxIo.h"
#include "cvxEMTreeSolver.h"

using namespace std;
using namespace cv;
using cvx::Rgb8UImage;
using cvx::Bw8UImage;

#if 0
int main(int argc, char **argv)
{
	char *orgFileName = argv[1];
	char *shaFileName = argv[2];

	if(argc != 3)
	{
		printf("usage: AdjustIntrinsicScale orgImageName shadingImageName\n");
		return 1;
	}
	printf("U for up, D for down, Esc for exit\n");

	float scale = 1.0;

	Mat orgImage = cv::imread(orgFileName, 1);
	Mat orgShadingImage = cv::imread(shaFileName, 0);  
//	Mat orgImage        = cv::imread("test_image\\synthetic_org\\synthetic.tif", 1);
//	Mat orgShadingImage = cv::imread("itereatedShading.png", 0);
	assert(!orgImage.empty());
	assert(!orgShadingImage.empty());

	cv::imshow("org image", orgImage);
	cv::imshow("org shading", orgShadingImage);

	int h = orgImage.rows;
	int w = orgImage.cols;
	
	Mat showReflectance = orgImage.clone();
	Mat showShading     = orgShadingImage.clone();

	while(1)
	{
		//calculate new shading
		orgShadingImage.convertTo(showShading, CV_8UC1, scale);

		//calculate new reflectance
		Bw8UImage new_sha(&showShading);
		Rgb8UImage org_img(&orgImage);
		Rgb8UImage new_ref(&showReflectance);
		for(int y = 0; y<h; y++)
		{
			for(int x = 0; x<w; x++)
			{
				float s = new_sha[y][x]/255.0;
				new_ref[y][x].r = org_img[y][x].r/s;
				new_ref[y][x].g = org_img[y][x].g/s;
				new_ref[y][x].b = org_img[y][x].b/s;
			}
		}
		printf("scale = %f\n", scale);
		cv::imshow("reflectance", showReflectance);
		cv::imshow("shading", showShading);
		cv::waitKey(10);

		char c = cv::waitKey(0);
		if(c == 'u' || c == 'U')
		{
			scale += 0.02;
		}
		else if(c == 'd' || c== 'D')
		{
			scale -= 0.02;
		}
		else if(c == 27)
		{
			break;
		}
		if(scale <= 0.0)
		{
			scale = 0.1;
		}
		
	}
	cv::imwrite("adjustedShading.png", showShading);
	cv::imwrite("adjustedReflectance.png", showReflectance);	

	return 1;
}

#endif